package cn.fancy.sdk;

import static cn.fancy.sdk.utils.SpMmkvUtils.KEY_VERTICAL_ORIENTATION;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import cn.fancy.sdk.common.utils.NetworkImpl;
import cn.fancy.sdk.configini.GuildConfigIni;
import cn.fancy.sdk.entity.GuildBaseInfo;
import cn.fancy.sdk.floatwindow.FloatWindowService;
import cn.fancy.sdk.floatwindow.MyWindowManager;
import cn.fancy.sdk.login.LoginViewActivity;
import cn.fancy.sdk.login.QdLoginCallback;
import cn.fancy.sdk.login.utils.DBHelper;
import cn.fancy.sdk.openwebview.OpenWebView;
import cn.fancy.sdk.pay.GuildPayActivity;
import cn.fancy.sdk.pay.QdPayCallback;
import cn.fancy.sdk.permission.InitPermissionActivity;
import cn.fancy.sdk.service.QdServiceSdk;
import cn.fancy.sdk.utils.CommMessage;
import cn.fancy.sdk.utils.SpMmkvUtils;
import cn.fancy.sdk.utils.TipMessSingle;
import com.bytedance.applog.AppLog;
import com.bytedance.applog.ILogger;
import com.bytedance.applog.InitConfig;
import com.bytedance.applog.game.GameReportHelper;
import com.bytedance.applog.util.UriConstants;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;

public class FancyManager {
    
    public QdServiceSdk serviceSDK;
    private DBHelper dbHelper;
    static private Handler statichandle = null;
    public QdRegisterCallback registerCallback = null;
    private Timer mTimer = new Timer();
    private Intent mFubiaoIntent = null;
    private boolean advertIdBool;
    private Context mContext;
    
    public static final String SERVER_ID = "serverId";
    public static final String SERVER_NAME = "serverName";
    public static final String ROLE_ID = "roleId";
    public static final String ROLE_NAME = "rolename";
    public static final String ROLE_LEVEL = "roleLevel";
    
    // 静态内部类实现单例模式
    private static class QdSdkManagerHolder {
        
        private static FancyManager instance = new FancyManager();
    }
    
    public static FancyManager getInstance() {
        return QdSdkManagerHolder.instance;
    }
    
    /**
     * @param propsId 道具ID
     * @param money 金额(单位元)
     * @param item_desc 商品描述
     * @param order 订单号
     */
    public void pay(Context context, String propsId, int money, String item_desc, String order, String cp_data, QdPayCallback listener) {
        // 当前没有网络连接
        if (!NetworkImpl.isNetworkConnected(context)) {
            Toast.makeText(context, TipMessSingle.ten_networkerr,
                Toast.LENGTH_LONG).show();
            return;
        }
        // 聚合传的money是10元，传给后台时是用1000分
        GuildPayActivity.start(context, propsId, money, item_desc, order, cp_data, listener);
    }
    
    public void login(Activity activity, QdLoginCallback icallback) {
        if (activity == null || icallback == null) {
            Toast.makeText(activity, "登录入参不能为空", Toast.LENGTH_LONG).show();
            throw new IllegalArgumentException("only MATCH_PARENT is supported.");
		}
        LoginViewActivity.start(activity, icallback);
    }
    
    public void showPermissionActivity(Activity activity) {
        InitPermissionActivity.start(activity, 1);
    }
    
    public void logout(Context context) {
        if (statichandle != null) {
            statichandle.sendEmptyMessage(0);
            CommMessage.currentUserName = "";
            CommMessage.currentPassword = "";
            CommMessage.havedlogin = false;
            
            hideFloat(context);
            Log.e("qdsdkmanagerlogout", "qdsdkmanagerlogout");
        }
    }
    
    public void setLogoutListen(Handler handle, Context cxt) {
        if (handle == null) {
            Toast.makeText(cxt, "注销对象不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        statichandle = handle;
    }
    
    //固定channelid
    public void init(Context context, String gameid, String loginkey, String advertId, QdRegisterCallback registerCallback) {
        mContext = context;
        GuildConfigIni.initParams();
        GuildConfigIni.setParams("gameid", gameid);
        GuildConfigIni.setParams("loginkey", loginkey);
        
        HashMap<String, String> mapGuild = GuildConfigIni.getParams();
        String channelid = mapGuild.get("channelid");
        if (channelid.length() == 3) {
            String tempChannelId = channelid;
            if (tempChannelId.charAt(0) == '0') {
                tempChannelId = tempChannelId.substring(1);
                if (tempChannelId.charAt(0) == '0') {
                    tempChannelId = tempChannelId.substring(1);
                    
                }
            }
            channelid = tempChannelId;
        }
        initPublic(context, gameid, channelid, loginkey, advertId, registerCallback);
    }
    
    public void initWithChannelId(Context context, String gameid, String channelid, String loginkey, String advertId, QdRegisterCallback registerCallback) {
        mContext = context;
        GuildConfigIni.initParams();
        GuildConfigIni.setParams("gameid", gameid);
        GuildConfigIni.setParams("channelid", channelid);
        GuildConfigIni.setParams("loginkey", loginkey);
        initPublic(context, gameid, channelid, loginkey, advertId, registerCallback);
    }
    
    private void initPublic(Context context, String gameid, String channelid, String loginkey, String advertId,
        QdRegisterCallback registerCallback){
        
        GuildBaseInfo.getInstance().init(context, gameid, channelid, loginkey);
    
        //=================此是字节巨量引擎数据收集 start
        //渠道包&有appid时使用
        if (!TextUtils.isEmpty(advertId)) {
            Log.d("FancyManager.initPublic", "advertId=" + advertId);
            advertIdBool = true;
            final InitConfig byteDanceConfig = new InitConfig(advertId, channelid);
            byteDanceConfig.setUriConfig(UriConstants.DEFAULT);
            // 是否在控制台输出⽇ 志，可⽤于观察⽤⼾⾏为⽇志上报情况，建议仅在调试时使⽤
            byteDanceConfig.setLogger(new ILogger() {
                @Override
                public void log(String s, Throwable throwable) {
                    Log.d("FancyManager.initPublic", s);
                }
            });
            // 是否开启游戏模式，游戏APP建议设置为 true
            byteDanceConfig.setEnablePlay(true);
            byteDanceConfig.setAbEnable(true); // 是否开启A/B Test功能
            byteDanceConfig.setAutoStart(true);
            AppLog.init(context, byteDanceConfig);
        }
        //=================此是字节巨量引擎数据收集 end
    
        String packagename = context.getPackageName();
        CommMessage.setMacFile(packagename); // 初始化 mac_file存放位置
        
        serviceSDK = new QdServiceSdk();
        serviceSDK.initCore(context, gameid, channelid);
        dbHelper = DBHelper.getInstance(context);
        // 添加注册回调
        this.registerCallback = registerCallback;
        FloatWindowService.AppContent = context;
        
        SpMmkvUtils.init(context);
    }
    
    public void rolestatis(Context context, Bundle bundle, String ac) {
        CommMessage.mapRoleInformation.put(FancyManager.SERVER_ID,
            bundle.getString(FancyManager.SERVER_ID));
        CommMessage.mapRoleInformation.put(FancyManager.SERVER_NAME,
            bundle.getString(FancyManager.SERVER_NAME));
        CommMessage.mapRoleInformation.put(FancyManager.ROLE_ID,
            bundle.getString(FancyManager.ROLE_ID));
        CommMessage.mapRoleInformation.put(FancyManager.ROLE_NAME,
            bundle.getString(FancyManager.ROLE_NAME));
        
        RoleStatis.sendStatis(context, bundle);
    
        if (advertIdBool) {
            switch (ac) {
                case RoleStatis.AC_CREATE_ROLE:
                    GameReportHelper.onEventCreateGameRole(bundle.getString(FancyManager.ROLE_ID));
                    break;
                case RoleStatis.AC_ROLE_LEVEL_UP:
                    String roleLevel = bundle.containsKey(FancyManager.ROLE_LEVEL) ? bundle.getString(FancyManager.ROLE_LEVEL) : "1";
                    //WhalerGameHelper.levelUp(Integer.parseInt(roleLevel), 0, "", Integer.parseInt(roleLevel), new HashMap<String, Object>()); //等级、经验、途径、等级、
                    GameReportHelper.onEventUpdateLevel(Integer.parseInt(roleLevel));
                    break;
                case RoleStatis.AC_ENTER_GAME:
                    GameReportHelper.onEventLogin(bundle.getString(FancyManager.ROLE_ID), true);
                    break;
            }
        }
    }
    
    public void Ondestroy() {
        FloatWindowService.canopenfloat = false;
    }
    
    public void onResume(Context context) {
        Log.e("qdsdkmanagerresume", "qdsdkmanagerresume");
        FloatWindowService.canopenfloat = true;
        
        IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
        filter.addDataScheme("package");
    
        if (advertIdBool) {
            AppLog.onResume(context);
        }
    }
    
    public void onPause(Context context) {
        FloatWindowService.canopenfloat = false;
    
        if (advertIdBool) {
            AppLog.onPause(context);
        }
    }
    
    public String getCmCertStatus() {
        return CommMessage.getCmCert();
    }
    
    public void showWebView(Context cxt, String url, Map<String, String> params) {
        Log.d("CommMessage",
            "OpenWebView:" + url + ",params:" + params == null ? ""
                : params.toString());
        if (!NetworkImpl.isNetworkConnected(cxt)) {
            Toast.makeText(cxt, TipMessSingle.ten_networkerr, Toast.LENGTH_LONG)
                .show();
            return;
        }
        OpenWebView.start(cxt, url, params);
    }
    
    public void CallRegister(int code, String mess) {
        if (registerCallback != null) {
            registerCallback.callback(code, mess);
        }
    }
    
    public void closeTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }
    
    public void showFloat(Context cxt) {
		if (mFubiaoIntent != null) {
            Log.e("floaterror", "mFubiaoIntent is null");
            return;
		}
		if (cxt == null) {
			Log.e("floaterror", "showFloat cxt is null");
			return;
		}
		mFubiaoIntent = new Intent(cxt.getApplicationContext(), FloatWindowService.class);
		FloatWindowService.canopenfloat = true;
		cxt.startService(mFubiaoIntent);
		FloatWindowService.isshowflat = false;
    }
    
    public void hideFloat(Context context) {
        if (mFubiaoIntent == null) {
            return;
        }
        if (context == null) {
            Log.e("floaterror", "showFloat cxt is null");
            return;
        }
        context.getApplicationContext().stopService(mFubiaoIntent);
        MyWindowManager.removefloatWindow(context.getApplicationContext());
        FloatWindowService.canopenfloat = false;
        mFubiaoIntent = null;
    }
    
    public void setVerticalOrientation(){
        SpMmkvUtils.putValue(mContext, KEY_VERTICAL_ORIENTATION, KEY_VERTICAL_ORIENTATION);
        Log.d("FancyManager", "FancyManager setVerticalOrientation ORIENTATION");
    }
    
    public boolean isAdvertIdBool() {
        return advertIdBool;
    }
    
    public Context getmContext() {
        return mContext;
    }
}
